package com.botann.projects.filter;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * StorageManager
 * SimpleCORSFilter
 * Created by 刘山国 on 2017/5/20.
 * Copyright (c) 2017 刘山国. All rights reserved.
 */
@Component
public class SimpleCORSFilter implements Filter {

    private Logger logger = Logger.getLogger(SimpleCORSFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

        HttpServletResponse response = (HttpServletResponse) res;
        HttpServletRequest request = (HttpServletRequest)req;
        response.setHeader("Access-Control-Allow-Origin",request.getHeader("Origin"));
//        response.setHeader("Access-Control-Allow-Origin","*");

        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers",
                "origin, Content-Type, Authorization, Accept, x-auth-code, X-App-Id, X-Token, x-csrftoken, X-Requested-With");
        // 这里设为true时,可以携带cookie,但是Access-Control-Allow-Origin不能设为*
        response.setHeader("Access-Control-Allow-Credentials","true");
//        response.setHeader("Set-Cookie", "cookiename=value; Path=/;Domain=domainvalue;Max-Age=seconds;HTTPOnly");
        chain.doFilter(req, res);
    }

    @Override
    public void destroy() {

    }
}
